package nio;


import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Arrays;

public class ScatteringAndGatheringTest {
    public static void main(String[] args) throws IOException {
        //创建
        ServerSocketChannel socketChannel = ServerSocketChannel.open();
        InetSocketAddress inetSocketAddress = new InetSocketAddress(7000);
        //绑定端口
        socketChannel.socket().bind(inetSocketAddress);

        //创建buffer数组
        ByteBuffer[] byteBuffers = new ByteBuffer[2];
        byteBuffers[0] = ByteBuffer.allocate(5);
        byteBuffers[1] = ByteBuffer.allocate(3);

        //等客户连接
        SocketChannel channel = socketChannel.accept();
        long messageLenght = 8;
        //循环读取
        while (true) {
            long byteRead = 0;
            while (byteRead < messageLenght) {
                long read = channel.read(byteBuffers);
                byteRead += read;
                System.out.println("byteRead===" + byteRead);
                //流打印
                Arrays.asList(byteBuffers).stream().map(buffer -> "postion==" + buffer.position() + "limit ==" + buffer.limit()).forEach(System.out::println);
            }
            //反转
            Arrays.asList(byteBuffers).stream().forEach(byteBuffer -> {
                byteBuffer.flip();
            });
            //数据读出显示到客户端
            long byteWrite = 0;
            while (byteWrite < messageLenght) {
                long write = channel.write(byteBuffers);
                byteWrite += write;
            }
            //复位
            Arrays.asList(byteBuffers).stream().forEach(byteBuffer -> {
                byteBuffer.clear();
            });
            System.out.println("messageLenght===" + messageLenght + "  byteRead===" + byteRead + "   byteWrite==" + byteWrite);
        }
    }
}
